package com.chuanghai.light.tcp;

public class Parser {
    private static final int IDLE = 1;
    private static final int STX1 = 2;
    private static final int STX2 = 3;
    private static final int STX3 = 4;
    private static final int TYPE = 5;
    private static final int LEN_H = 6;
    private static final int LEN_L= 7;
    private static final int DATA = 8;
    private static final int FCS1 = 9;
    private static final int FCS2 = 10;

    private static boolean msg_received;

    private Packet packet = null;

    private int states = IDLE;

    public Packet message_parse_char(byte b) {
        msg_received = false;
       //System.out.printf("%02x\r\n",b);
        switch (states + 1) {
            case STX1:
                //System.out.println("STX1");
                if (b == Packet.MESSAGE_STX1)  states = STX1;
                else                           states = IDLE;
                break;
            case STX2:
                //System.out.println("STX2");
                if (b == Packet.MESSAGE_STX2)  states = STX2;
                else                           states = IDLE;
                break;
            case STX3:
                //System.out.println("STX3");
                if (b == Packet.MESSAGE_STX3)  states = STX3;
                else                           states = IDLE;
                break;
            case TYPE:
                //System.out.println("TYPE");
                packet = new Packet();
                packet.type = b;
                states = TYPE;
                break;
            case LEN_H:
                //System.out.println("LEN_H");
                states = LEN_H;
                packet.len = b;
                break;
            case LEN_L:
                //System.out.println("LEN_L");
                states = LEN_L;
                packet.len = packet.len<<8 | b;
                packet.setPayloadLength(packet.len);
                break;
            case DATA:
               // System.out.println("DATA");
                packet.payload.add(b);
                if (packet.payloadIsFilled()) {
                    states = IDLE;
                    msg_received = true;
                }
                break;
            default:
                states = IDLE;
                break;
        }
        return msg_received ? packet : null;
    }
}